package com.jsb.laundry.common.utils.thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 线程工具类
 *
 * @author zmy
 * @create 2023-02-02 23:11
 */
public class ThreadUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(ThreadUtil.class);

    /**
     * 核心线程池大小
     */
    private static final int POOL_SIZE = 50;

    /**
     * 最大可创建的线程数
     */
    private static final int MAX_POOL_SIZE = 200;

    /**
     * 队列最大长度
     */
    private static final int QUEUE_CAPACITY = 1000;

    /**
     * 线程池维护线程所允许的空闲时间
     */
    private static final int KEEPALIVE_SECONDS = 300;

    private static ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE);

    /**
     * 开启执行多线程
     *
     * @param tasks
     */
    public static void runTasks(Runnable... tasks) {
        for (Runnable task : tasks) {
            executor.submit(task);
        }
        executor.shutdown();
        try {
            executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            LOGGER.info("InterruptedException:" + e);
        }
    }

    /**
     * sleep等待,单位为毫秒
     */
    public static void sleep(long milliseconds) {
        try {
            Thread.sleep(milliseconds);
        } catch (InterruptedException e) {
            return;
        }
    }

}
